package com.allwees.bs.module.mms.service.impl;

import com.allwees.bs.module.base.service.impl.BoServiceImpl;
import com.allwees.bs.module.mms.dao.SupplierApplyDao;
import com.allwees.bs.module.mms.entity.SupplierApply;
import com.allwees.bs.module.mms.req.SupplierApplyAuditReq;
import com.allwees.bs.module.mms.service.SupplierApplyService;
import com.allwees.bs.module.mms.wf.ESupplierApplyAction;
import com.allwees.bs.module.mms.wf.ESupplierApplyState;
import com.allwees.core.common.constant.EStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.allwees.bs.module.mms.wf.ESupplierApplyAction.PLATFORM_FINAL_APPROVED;
import static com.allwees.bs.module.mms.wf.ESupplierApplyAction.PLATFORM_FINAL_REJECTED;
import static com.allwees.bs.module.mms.wf.ESupplierApplyAction.PLATFORM_FIRST_APPROVED;
import static com.allwees.bs.module.mms.wf.ESupplierApplyAction.PLATFORM_FIRST_REJECTED;

/**
 *
 *
 * @author yangylsky
 * @since 2019-12-03
 *
 */
@Service
public class SupplierApplyServiceImpl extends BoServiceImpl<SupplierApplyDao, SupplierApply> implements SupplierApplyService {

    @Override
    @Transactional
    public void audit(SupplierApplyAuditReq req) {
        for (String uuid : req.getSupplierApplyUuids()) {
            SupplierApply supplierApply = findByUuid(uuid);

            if (org.apache.commons.lang3.StringUtils.isBlank(supplierApply.getFirstAuditUserUuid())) {
                supplierApply.setFirstAuditUserUuid(req.getBranchUserUuid());
            } else if (org.apache.commons.lang3.StringUtils.isBlank(supplierApply.getFinalAuditUserUuid())) {
                supplierApply.setFinalAuditUserUuid(req.getBranchUserUuid());
            }

            ESupplierApplyAction action = _auditAction(EStatus.byValue(supplierApply.getStatus()), req.isApproved());
            supplierApply.signal(action, req.getReason(), req.getRemark(), req.getPhotos());
            updateByUuid(supplierApply);
        }
    }

    @Override
    public String findAuditStatus(String phone) {
        SupplierApply supplierApply = baseMapper.selectByPhone(phone);
        return supplierApply == null ? "手机号不存在" : ESupplierApplyState.valueOf(supplierApply.getState()).desc();
    }

    private ESupplierApplyAction _auditAction(EStatus status, boolean approved) {
        switch (status) {
            case WAIT_AUDIT:
                return approved ? PLATFORM_FIRST_APPROVED : PLATFORM_FIRST_REJECTED;
            case MMS_FIRST_AUDIT_APPROVED:
                return approved ? PLATFORM_FINAL_APPROVED : PLATFORM_FINAL_REJECTED;
			default:
				break;
        }
        return null;
    }
}
